import { App, ConfigProvider, Modal, locales } from 'antd';
import React, { useReducer } from 'react';
import { theme } from '../config';
import './useModal.module.css';

export default function useModal() {
  const { modal } = App.useApp();
  const [state, dispatch] = useReducer((state, action) => ({ ...state, ...action }), {
    open: false,
    props: {},
  });

  function destroy() {
    dispatch({ open: false });
  }

  function OpenSlot() {
    const { content, onOk, ...rest } = state.props;
    return (
      <Modal wrapClassName={["mp-dialog", (!rest.title ? "mp-dialog-no-title" : "")].join(' ')}
        onOk={() => {
          if (!onOk) return destroy();
          const ok = onOk();
          if (ok instanceof Promise) {
            ok.then((res) => res === false || destroy());
          } else {
            if (ok !== false) destroy();
          }
        }} onCancel={destroy} destroyOnClose {...rest} open={state.open}>
        {content}
      </Modal>
    )
  }

  function ModalMethod(name, { content, ...props }) {
    modal[name]({
      wrapClassName: ["mp-dialog", (!props.title ? "mp-dialog-no-title" : "")].join(' '),
      content: <ConfigProvider locale={locales.zh_CN} theme={theme}>{content}</ConfigProvider>,
      ...props
    });
  }

  return [{
    open(props) {
      dispatch({ open: true, props });
      return { destroy };
    },
    info: (props) => ModalMethod('info', props),
    success: (props) => ModalMethod('success', props),
    error: (props) => ModalMethod('error', props),
    warning: (props) => ModalMethod('warning', props),
    confirm: (props) => ModalMethod('confirm', props),
  }, <OpenSlot />];
};